import { defineStore } from 'pinia'
import { ref } from 'vue'
import router from '../../router'
import { login as loginApi } from '../../api/user'

const useUserStore = defineStore('user', () => {
    // 用户信息
    const userInfo = ref({})

    // token
    const token = ref('')

    // 保存token
    const setToken = val => {
        token.value = val
    }

    // 保存用户信息
    const setUserInfo = info => {
        userInfo.value = info
    }

    // 登录
    const login = (data) => {
        return new Promise((resolve, reject) => {
            loginApi(data)
                .then(res => {
                    const { data, message } = res
                    console.log(data)
                    setToken(data.token)
                    setUserInfo(data)
                    router.replace('/')
                    ElMessage.success(message)
                    resolve()
                }).catch(err => {
                    reject(err)
                })
        })
    }

    // 注销
    const logout = () => {
        setToken('')
        setUserInfo('')
        localStorage.clear()
        router.replace('/login')
    }

    return {
        token,
        userInfo,
        login,
        logout
    }
}, {
    persist: true, // 持久化存储
})

export default useUserStore